package com.guigu.eduservice.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.guigu.eduservice.entity.BargainIntention;
import com.guigu.eduservice.entity.Equipment;
import com.guigu.eduservice.entity.EquipmentReservation;
import com.guigu.eduservice.entity.Order;
import com.guigu.eduservice.mapper.BargainIntentionMapper;
import com.guigu.eduservice.service.BargainIntentionService;
import com.guigu.eduservice.service.EquipmentReservationService;
import com.guigu.eduservice.service.EquipmentService;
import com.guigu.eduservice.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;
import java.util.List;

@Service
public class BargainIntentionImpl extends ServiceImpl<BargainIntentionMapper, BargainIntention> implements BargainIntentionService {
    @Autowired
    private BargainIntentionMapper bargainIntentionMapper;
    @Autowired
    private OrderService orderService;
    @Autowired
    private EquipmentService equipmentService;
    @Autowired
    private EquipmentReservationService equipmentReservationService;

    @Override
    public PageInfo<BargainIntention> getBargainIntentionList(int pageNum, int pageSize) {
        PageHelper.startPage(pageNum,pageSize);

        List<BargainIntention> bargainIntentionList = bargainIntentionMapper.selectList(null);
        return new PageInfo<>(bargainIntentionList);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)// 事务注解：所有异常都回滚，保证原子性
    public boolean updateBargainIntention(Long bargainId) {
        //先查询砍价列表
        BargainIntention bargainIntention = bargainIntentionMapper.selectById(bargainId);
        if (bargainIntention == null){
            return false;
        }
        // 3. 避免重复处理（关键！防止重复生成订单/预定记录）
        if (bargainIntention.getBargainStatus() != 1) { // 仅状态为1（商户同意）时处理
            return true;
        }
        //通过设备ID拿到卖家ID
        LambdaQueryWrapper<Equipment> Eqwrapper = new LambdaQueryWrapper<>();
        Eqwrapper.eq(Equipment::getEquipmentId,bargainIntention.getEquipmentId());
        Equipment equipment = equipmentService.getOne(Eqwrapper);
        if (equipment==null){
            return false;
        }
        //获取卖家ID
        Long sellerId = equipment.getUserId();
        if (sellerId==null){
            return false;
        }
        //  意向价格非空+合法性校验（避免BigDecimal空指针/无效金额）
        BigDecimal intentionPrice = bargainIntention.getIntentionPrice();
        if (intentionPrice == null || intentionPrice.compareTo(BigDecimal.ZERO) < 0) {
            return false; // 价格为空或负数，直接返回失败
        }

        try {
            // 7. 事务注解：保证「生成订单+保存预定+修改设备」原子性（要么全成，要么全回滚）
            if (bargainIntention.getBargainStatus() == 1) {
                //生成订单前我得判断这个设备已经在订单里面存在了
                LambdaQueryWrapper<Order> orderLambdaQueryWrapper = new LambdaQueryWrapper<>();
                orderLambdaQueryWrapper.eq(Order::getEquipmentId, bargainIntention.getEquipmentId());
                orderLambdaQueryWrapper.eq(Order::getBuyerId, bargainIntention.getUserId());
                Order bargainIntention1 = orderService.getOne(orderLambdaQueryWrapper);
                if (bargainIntention1 != null){
                    return false;
                }
                // 生成订单
                Order order = new Order();
                order.setBuyerId(bargainIntention.getUserId());
                order.setSellerId(sellerId);
                order.setEquipmentId(bargainIntention.getEquipmentId());
                order.setOrderAmount(intentionPrice); // 直接用校验后的非空价格

                // 计算30%押金（已做非空校验，可安全调用）
                BigDecimal depositRatio = new BigDecimal("0.3");
                BigDecimal depositAmount = intentionPrice.multiply(depositRatio)
                        .setScale(2, RoundingMode.HALF_UP);
                order.setDepositAmount(depositAmount);

                // 计算尾款（双重防护：避免极端情况下的空值）
                BigDecimal balanceAmount = BigDecimal.ZERO;
                if (order.getOrderAmount() != null && order.getDepositAmount() != null) {
                    balanceAmount = order.getOrderAmount().subtract(order.getDepositAmount());
                }
                order.setBalanceAmount(balanceAmount);
                order.setOrderStatus(0); // 待支付定金
                orderService.save(order);

                // 生成预定表
                EquipmentReservation equipmentReservation = new EquipmentReservation();
                equipmentReservation.setUserId(bargainIntention.getUserId());
                equipmentReservation.setEquipmentId(bargainIntention.getEquipmentId());
                equipmentReservation.setReservationDeposit(depositAmount); // 复用已计算的押金
                equipmentReservation.setReservationStatus(0);
                // 1. 设置预定周期（保留原有逻辑，建议补充非空校验）
                Integer reservationPeriod = 3; // 可替换为变量（如从配置/参数获取）
                // 预定周期非空+非负校验（避免负数天数导致过期时间异常）
                if (reservationPeriod == null || reservationPeriod < 0) {
                    reservationPeriod = 3; // 默认3天，或抛出异常
                }
                equipmentReservation.setReservationPeriod(reservationPeriod);

                // 2. 计算过期时间：当前时间 + reservationPeriod 天
                LocalDateTime now = LocalDateTime.now(); // 获取当前时间（包含时分秒）
                LocalDateTime expireLocalDateTime = now.plusDays(reservationPeriod); // 加指定天数
                // 转换为 Date 类型（适配实体类的 Date 字段）
                ZoneId zoneId = ZoneId.systemDefault(); // 系统默认时区（如 UTC+8）
                Instant expireInstant = expireLocalDateTime.atZone(zoneId).toInstant();
                Date expireTime = Date.from(expireInstant);

                // 3. 设置过期时间
                equipmentReservation.setExpireTime(expireTime);
                equipmentReservationService.save(equipmentReservation);

                // 修改设备状态（锁定设备）
                equipment.setStatus(2);
                equipmentService.update(equipment, Eqwrapper);
            }
            return true;
        } catch (Exception e) {
            System.out.println("卖同意处报错");
            return false;
        }
    }


}
